package reci.journal;

import java.io.*;
import java.util.Properties;

import reci.journal.utils.ExtUtil;

/*
 * Copyright (C) 2014 ReciGames
 * See notice in reci.journal.Main.java.
 */

/**global settings*/
public class GlobalSettings
{
	/**directory for global settings file*/
	private static final String SETTINGS_DIR=getSettingsDirectoryPath();
	/**global settings filename*/
	private static final String SETTINGS_NAME=".settings";
	/**global settings path*/
	private static final String SETTINGS_PATH=SETTINGS_DIR+SETTINGS_NAME;
	
	/**global settings*/
	private static Properties props=new Properties();
	private static boolean arePropsLoaded=false;
	
	/**
	 * Ensures settings are loaded.
	 */
	private static void ensureSettingsLoaded()
	{
		if(arePropsLoaded)
		{
			return;
		}
		
		props=new Properties();
		
		try
		{
			BufferedReader r=new BufferedReader(new FileReader(SETTINGS_PATH));
			props.load(r);
			r.close();
		}
		catch(Exception e)
		{}
		
		arePropsLoaded=true;
	}
	
	/**
	 * Sets a property.
	 * 
	 * @param key
	 * @param value
	 */
	public static void setProperty(String key, String value)
	{
		props.setProperty(key,value);
	}
	
	/**
	 * Writes settings to file.
	 */
	public static void writeSettings()
	{
		BufferedWriter bw=null;
		
		try
		{
			new File(SETTINGS_DIR).mkdirs();
			bw=new BufferedWriter(new FileWriter(SETTINGS_PATH));
			props.store(bw,"Global Settings");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			ExtUtil.close(bw);
		}
	}
	
	/**
	 * @return default path for .rj files
	 */
	public static String getDefaultRjPath()
	{
		ensureSettingsLoaded();
		
		if(props.containsKey(Keys.DEFAULT_RJPATH))
		{
			return props.getProperty(Keys.DEFAULT_RJPATH);
		}
		
		return "";
	}
	
	/**
	 * @return OS-specific path for app data
	 */
	private static String getSettingsDirectoryPath()
	{
		StringBuffer sb=new StringBuffer();
		
		String os=System.getProperty("os.name").toLowerCase();
		
		//windows
		if(os.contains("win"))
		{
			sb.append(System.getenv("ALLUSERSPROFILE"));
//				sb.append(System.getenv("APPDATA"));
		}
		//mac
		else if(os.contains("mac"))
		{
			sb.append(System.getProperty("user.home"));
			sb.append("/Library/Application Support");
		}
		//linux
		else if(os.contains("nux"))
		{
			sb.append(System.getenv("user.home"));
		}
		//default
		else
		{
			sb.append(System.getenv("user.dir"));
		}
		
		sb.append(File.separator);
		sb.append(Const.APP_NAME);
		sb.append(File.separator);
		
		return sb.toString();
	}
}
